<?php

namespace App\Service\Cruise\Check;

use App\Models\Common\FileTranscodingJobModel;
use App\Models\Cruise\CruiseCheckAlbumModel;
use App\Service\BaseService;
use App\Service\Common\OssService;
use App\Service\Common\UploadTranscoding;
use App\Service\Cruise\Generic\CreateWatermarkPng;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Kuafu\File\FileUtil;
use OSS\Core\OssException;

class CruiseCheckFileDisposeService extends BaseService
{

    /**
     * 图片加水印
     * @param $url
     * @param $info
     * @param $userName
     * @param $address
     * @param $module
     * @return array
     * @throws OssException
     */
    public static function getFileWatermark($url, $info, $userName, $address, $module): array
    {
        ini_set('memory_limit', '1024M');
        //$url = FileUtil::domain() . '/' . $file;
        if (!Str::contains($url, [FileUtil::domain(), 'https://file.51kuafu.com'])) {
            $url = FileUtil::domain() . '/' . $url;
        }
        // 处理IOS图片旋转问题
        $file_extension = pathinfo($url, PATHINFO_EXTENSION);
        $localImage     = $url;
        $unsetImage     = false;
        try {
            if (in_array($file_extension, ['png', 'jpeg', 'jpg'])) {
                $localImage = sys_get_temp_dir() . '/' . Str::random() . '.' . $file_extension;
                $unsetImage = true;
                (new Client())->get($url, [
                    'sink' => $localImage,
                ]);

                if ($file_extension == 'png') {
                    $imageResource = imagecreatefrompng($localImage);
                } else {
                    $imageResource = imagecreatefromjpeg($localImage);
                }

                $exif = exif_read_data($url);

                if(!empty($exif['Orientation'])) {
                    switch($exif['Orientation']) {
                        case 8:
                            $imageRes = imagerotate($imageResource,90,0);
                            break;
                        case 3:
                            $imageRes = imagerotate($imageResource,180,0);
                            break;
                        case 6:
                            $imageRes = imagerotate($imageResource,-90,0);
                            break;
                        default:
                            $imageRes = false;
                    }

                    if ($imageRes) {
                        imagejpeg($imageRes, $localImage);
                    }
                }
            }
        } catch (\Exception $exception) {}

        $photo = Image::make($localImage);
        $imageInfo = getimagesize($localImage);
        //获得水印图片
        $watermarkPng = CreateWatermarkPng::getWatermarkPng(Carbon::now()->format('Y-m-d H:i'), $info, $address, $userName, $module);
        $watermarkInfo = getimagesize($watermarkPng);
        $watermark = Image::make($watermarkPng);
        //根据宽图和扁图去添加水印
        $fixed = min($imageInfo[0], $imageInfo[1]);
        $rate = (float)((int)($fixed / 18 * 6) / $watermarkInfo['0']);
        $watermark->resize((int)( $watermarkInfo['0'] * $rate), (int)( $watermarkInfo['1'] * $rate));  // 重置比例
        $watermarkFile = 'watermark' . time() . '.png';
        $watermark->save(sys_get_temp_dir() . '/' . $watermarkFile);
        $photo->insert(sys_get_temp_dir() . '/' . $watermarkFile, 'bottom-left', (int)($imageInfo['0'] / 36), (int)($imageInfo['0'] / 36));  //添加水印
        $resFile = md5(time() . rand(10, 99)) . '.jpg';
        $photo->save(sys_get_temp_dir() . '/' . $resFile);
        $arr = OssService::uploadFile(sys_get_temp_dir() . '/' . $resFile);
        if ($unsetImage) {
            @unlink($localImage);
        }
        @unlink(sys_get_temp_dir() . '/' . $resFile);
        @unlink($watermarkPng);
        @unlink(sys_get_temp_dir() . '/' . $watermarkFile);
        return $arr;
    }


    //视频加水印

    /**
     * @param $cruiseOrderId
     * @param $file
     * @param $relationId
     * @param $info
     * @param $userName
     * @param $address
     * @param $module
     * @param int $isAlbum
     * @throws OssException
     */
    public static function getVideoWatermark($cruiseOrderId, $file, $relationId, $info, $userName, $address, $module, $isAlbum = 1)
    {
        ini_set('memory_limit', '1024M');
        if (strpos($file, FileUtil::domain()) !== false) {
            $file = ltrim(parse_url($file, PHP_URL_PATH), '/');
        }
        $cruiseCheckAlbumId = 0;
        if ($isAlbum) {
            //入库
            $cruiseCheckAlbumId = CruiseCheckAlbumModel::query()->create(
                [
                    'type'       => CruiseCheckAlbumModel::TYPE_VIDEO,
                    'url'        => $file,
                    'relationId' => $relationId,
                    'cruiseOrderId' => $cruiseOrderId,
                    'status'     => CruiseCheckAlbumModel::STATUS_UNUSED,
                    'module'     => $module,
                    'isDeleted'  => 1
                ]
            )->id;
        }

        //获得水印图片
        $watermarkPng = CreateWatermarkPng::getWatermarkPng(Carbon::now()->format('Y-m-d H:i'), $info, $address, $userName, $module);
        //上传OSS
        $watermarkPath = 'tmp/' . Carbon::now()->format('Ymd') . '/' . Str::random(8) . '.png';
        $watermarkOss = OssService::uploadFile($watermarkPng, null, $watermarkPath);
        $jobId                                 = UploadTranscoding::asyncFileTranscoding($file, config('file-transcoding.kf-file'), $watermarkOss['path']);
        $fileTranscodingModel                  = new FileTranscodingJobModel();
        $fileTranscodingModel->jobId           = $jobId;
        $fileTranscodingModel->model           = CruiseCheckAlbumModel::class;
        $fileTranscodingModel->filePath        = $file;
        $fileTranscodingModel->updatedField    = 'url';
        $fileTranscodingModel->updatedModelId  = $cruiseCheckAlbumId;
        $fileTranscodingModel->filePathEncoded = substr($file, 0, strrpos($file, '.')) . '_encoded.mp4';
        $fileTranscodingModel->status          = FileTranscodingJobModel::STATUS_WAIT;
        $fileTranscodingModel->save();
    }


}
